﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace TathamOddie.OpenSearchValidator.Logic.Tasks.Description
{
	public class RetrieveOpenSearchDescriptionTask : IValidationTask
	{
		const string OpenSearchDescriptionMediaType = "application/opensearchdescription+xml";

		string descriptionPath;

		public RetrieveOpenSearchDescriptionTask(string descriptionPath)
		{
			this.descriptionPath = descriptionPath;
		}

		public ValidationTaskResult Validate(ValidationServices services, ValidationState state)
		{
			var result = new ValidationTaskResult();

			Uri queryUri;
			try
			{
				queryUri = new Uri(state.PageUri, descriptionPath);
			}
			catch (FormatException)
			{
				result.AddMessage(MessageType.Failure, "Failed to parse [{0}] as a URI.", descriptionPath);
				return result;
			}

			var description = DownloadHelper.Download
			(
				services.WebLoader,
				result,
				"description",
				false,
				queryUri,
				OpenSearchDescriptionMediaType
			);

			if (description != null)
			{
				result.ChildTasks.Add(new ValidateOpenSearchDescriptionTask(queryUri, description.Content));
			}

			return result;
		}
	}
}